<template>
  <scroll-view
    class="letter"
    ref="letter"
    scroll-x="true"
    :scroll-left="scrollDistance"
    @scroll="scroll($event)"
  >
    <view
      :class="{
        letter_container: !isBeyond,
        letter_container_active: isBeyond,
      }"
      ref="letter_container"
    >
      <view
        :id="'letter_content' + index"
        class="letter_content"
        v-for="(item, index) in letterObject"
        :key="index"
      >
        <view
          v-for="(word, i) in item"
          :key="i"
          @click="choose(word, i, index, $event)"
          :data-disabled="index > isCanClickIndex || isShowAnswer"
        >
          <input
            type="text"
            :value="word.letter"
            :disabled="true"
            :class="{
              active: word.isSelect,
              correct: word.isCorrect && isShowAnswer,
              error: word.isSelect && !word.isCorrect && isShowAnswer,
            }"
          />
        </view>
      </view>
    </view>
  </scroll-view>
</template>
<script>
import { arrayRandomly } from "@/libs/tools";
export default {
  props: {
    word: {
      type: String,
      default: "",
    },
  },
  watch: {
    word() {
      this.initWord();
      this.init();
    },
  },
  created() {
    this.init();
  },
  mounted() {
    this.initLeft();
  },
  data() {
    return {
      answerArray: [],
      correctArray: [],
      errorArray1: [],
      errorArray2: [],
      letterObject: [],
      activeIndex: -1,
      activeI: -1,
      isCanClickIndex: 0,
      isShowAnswer: false,
      isSyllabic: false,
      scrollDistance: 0,
      scrollNumber: 54,
      scrollTime: 360,
      isBeyond: false,
      answerLength: 0,
      firstLeft: 0,
      currnetLeft: 0,
      noNeedFirstScroolNumber: 4,
      noNeedLastScroolNumber: 2,
    };
  },
  methods: {
    init() {
      if (this.word.length > 6) {
        this.isBeyond = true;
      } else {
        this.isBeyond = false;
      }
      this.correctArray = this.word.split("");
      for (let i = 0; i < this.correctArray.length; i++) {
        let randomNumber = Math.ceil(Math.random() * 25);
        let letter = String.fromCharCode(97 + randomNumber);
        if (letter == this.correctArray[i]) {
          i--;
          continue;
        }
        this.errorArray1.push(String.fromCharCode(97 + randomNumber));
      }
      for (let i = 0; i < this.correctArray.length; i++) {
        let randomNumber = Math.ceil(Math.random() * 25);
        let letter = String.fromCharCode(97 + randomNumber);
        if (letter == this.correctArray[i] || letter == this.errorArray1[i]) {
          i--;
          continue;
        }
        this.errorArray2.push(String.fromCharCode(97 + randomNumber));
      }
      this.correctArray.forEach((element, index) => {
        this.letterObject[index] = [
          {
            letter: element,
            isSelect: false,
            isCorrect: true,
          },
        ];
      });
      this.errorArray1.forEach((element, index) => {
        this.letterObject[index].push({
          letter: element,
          isSelect: false,
          isCorrect: false,
        });
      });
      this.errorArray2.forEach((element, index) => {
        this.letterObject[index].push({
          letter: element,
          isSelect: false,
          isCorrect: false,
        });
      });
      this.letterObject.forEach((element, index) => {
        this.letterObject[index] = arrayRandomly(element);
      });
      this.letterObject = JSON.parse(JSON.stringify(this.letterObject));
    },
    initLeft() {
      const query = uni.createSelectorQuery().in(this);
      query
        .select("#letter_content" + this.answerLength)
        .boundingClientRect((data) => {
          this.firstLeft = data.left;
        })
        .exec();
    },
    initWord() {
      this.answerArray = [];
      this.correctArray = [];
      this.errorArray1 = [];
      this.errorArray2 = [];
      this.letterObject = [];
      this.activeIndex = -1;
      this.activeI = -1;
      this.isCanClickIndex = 0;
      this.isShowAnswer = false;
      this.isSyllabic = false;
    },
    choose(word, i, index, e) {
      if (e.target.dataset.disabled) return;
      if (this.isCanClickIndex !== this.correctArray.length) {
        this.isCanClickIndex = index + 1;
      }
      for (let j = 0; j < this.letterObject[index].length; j++) {
        if (j === i) {
          this.letterObject[index][j].isSelect = true;
        } else {
          this.letterObject[index][j].isSelect = false;
        }
      }
      this.answerArray[index] = word.letter;
      this.$emit("updateAnswer", this.answerArray);
    },
    showAnswer(answer) {
      if (answer === this.word) {
        this.$emit("answerInformation", true);
      } else {
        this.$emit("answerInformation", false);
      }
      this.isShowAnswer = true;
    },
    checkLetter(answer) {
      this.answerArray = answer;
      this.isCanClickIndex = answer.length;
      this.letterObject.forEach((item, index) => {
        for (let i = 0; i < item.length; i++) {
          if (item[i].letter === answer[index]) {
            item[i].isSelect = true;
          } else {
            item[i].isSelect = false;
          }
        }
      });
      if (this.isSyllabic) {
        if (answer.join("") === this.word) {
          this.isShowAnswer = true;
          this.$emit("answerInformation", true);
        }
      }
      if (this.isBeyond) {
        if (
          answer.length > this.correctArray.length ||
          answer.length >=
            this.correctArray.length - this.noNeedLastScroolNumber ||
          answer.length < this.noNeedFirstScroolNumber
        )
          return;
        if (answer.length === 0) {
          this.scrollDistance = 0;
          return;
        }
        if (answer.length > this.answerLength) {
          const query = uni.createSelectorQuery().in(this);
          query
            .select("#letter_content" + (answer.length - 1))
            .boundingClientRect((data) => {
              this.currnetLeft = data.left;
              if (this.currnetLeft >= 216 + this.firstLeft) {
                this.handleScroll(this.scrollNumber, this.scrollTime);
              }
            })
            .exec();
        } else if (answer.length < this.answerLength) {
          this.handleScroll(-this.scrollNumber, this.scrollTime);
        }
        this.answerLength = answer.length;
      }
    },
    checkRightAndWrong(answer) {
      if (answer === this.word) {
        this.$emit("answerInformation", true);
      } else {
        this.$emit("answerInformation", false);
      }
    },
    initSyllabic(flag) {
      this.isSyllabic = flag;
      this.isShowAnswer = false;
      this.isCanClickIndex = 0;
      this.answerArray = [];
      this.letterObject.forEach((item) => {
        for (let i = 0; i < item.length; i++) {
          if (item[i].isSelect === true) {
            item[i].isSelect = false;
          }
        }
      });
    },
    scroll(e) {
      this.scrollDistance = e.target.scrollLeft;
    },
    handleScroll(distance, time) {
      let speed = 360;
      let count = Number.parseInt(time / speed);
      let length = distance / count;
      let timer = setInterval(() => {
        if (count > 0) {
          count--;
          this.scrollDistance = length + this.scrollDistance;
        } else {
          clearInterval(timer);
        }
      }, speed);
    },
  },
};
</script>
<style scoped lang="scss">
@import "./Keyboard";
</style>
